package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.CategoryMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealMapper;
import com.sky.pojo.Category;
import com.sky.result.PageResult;
import com.sky.service.common.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    static Integer categoryType;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */

    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        //属性拷贝
        BeanUtils.copyProperties(categoryDTO, category);
        //设置时间和操作人
       /* category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());*/

        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.insert(category);
        //   将缓存数据 清理
        redisTemplate.delete(RedisConstant.CATEGORY_LIST+categoryType);
    }

    /**
     * 分页查询
     *
     * @param categoryPageQueryDTO
     * @return
     */
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id删除分类
     *
     * @param id
     */
    public void deleteById(Long id) {
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Integer count = dishMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除分类数据
        categoryMapper.deleteById(id);
        //   将缓存数据 清理
        redisTemplate.delete(RedisConstant.CATEGORY_LIST+categoryType);
    }

    /**
     * 修改分类
     *
     * @param categoryDTO
     */
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        //设置修改时间和修改人
        /* category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());*/
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
        //   将缓存数据 清理
        redisTemplate.delete(RedisConstant.CATEGORY_LIST + categoryType);
    }

    /**
     * 启用、禁用分类
     *
     * @param status
     * @param id
     */

    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                /*.updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())*/
                .build();
        categoryMapper.update(category);
        //   将缓存数据 清理
        redisTemplate.delete(RedisConstant.CATEGORY_LIST + categoryType);

    }

    /**
     * 根据类型查询分类
     *
     * @param type
     * @return
     */
    @Autowired
    private RedisTemplate redisTemplate;

    public List<Category> list(Integer type) {
        categoryType = type;

        String key = RedisConstant.CATEGORY_LIST + type;

        try {
            List<Category> list = (List<Category>) redisTemplate.opsForValue().get(key);

            if (list == null) {
                // 缓存未命中，从数据库查询
                list = categoryMapper.list(type);

                // 设置合理的过期时间，避免数据长期不更新
                if (list != null && !list.isEmpty()) {
                    redisTemplate.opsForValue().set(key, list, Duration.ofHours(1));
                } else {
                    // 空结果缓存较短时间
                    redisTemplate.opsForValue().set(key, Collections.emptyList(), Duration.ofMinutes(5));
                }
            }

            return list != null ? list : Collections.emptyList();

        } catch (Exception e) {
            log.warn("获取分类列表缓存失败，直接查询数据库", e);
            // 缓存异常时直接查询数据库
            return categoryMapper.list(type);
        }
    }
}
